package com.zckj.jcServer;

import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;

import com.zckj.handle.MonitorBYJCProtocol;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.zckj.util.Constant;
import com.zckj.util.JCDataUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.eclipse.paho.client.mqttv3.MqttException;

/**
 * tcp服务操作数据类
 * @author ZCKJ
 *
 */
public class ServerHandle extends ChannelInboundHandlerAdapter {
	
	private static  final Logger  log  = Logger.getLogger(ServerHandle.class);
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException, MqttException {
		/*//数据缓存bytebuf数组
		ByteBuf buf = (ByteBuf) msg;
		//byte数组
		byte[] b = new byte[buf.readableBytes()];
		//把数据放入byte数组ֵ
		buf.readBytes(b);
		log.info(bytesToHexString(b));*/

		MonitorBYJCProtocol monitor = (MonitorBYJCProtocol) msg;
		byte[] head = int2Bytes(monitor.getHead_data());
		byte[] body = monitor.getContent();
		//合并两个数组
		byte[] b = byteMerger(head,body);
		//获取客户端ip地址ַ
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel()
				.remoteAddress();
		String clientIP = insocket.getAddress().getHostAddress();
		//获取客户端主机名称
		String clientName = insocket.getHostName();
		
		log.info("客户端IP"+clientIP+"客户端主机名称"+clientName);
		String account = "JCClient";
		String password = "123456";
		String clientId = "JC@SendData";
		String topic = "monitor/jc/data";
		MiddlewareMqttClient client = new MiddlewareMqttClient(Constant.HMQTTHOST,Constant.MQTTPORT,account,password,clientId,topic);
		client.init();
		//采集数据逻辑处理
		if (b[0] == 126) {
			String url = ""+Constant.HTTPURL;
			try {
				switch (b[13]) {
					case 80: // 传感器指令数据处理
						try{
							JSONObject object = JCDataUtil.parseJCData(b);
							client.publishMessage(topic,object.toJSONString());
//							JSONObject json = HttpUtil.httpPost(url, object,false);
//							log.info("请求服务器状态"+json.get("result").toString());
						}catch (Exception e) {
							e.printStackTrace();
						}
						
						break;

					case 96: // 门状态指令数据处理
						JSONObject object1 = JCDataUtil.parseDoorStateOne(b);
						client.publishMessage(topic,object1.toJSONString());
//						JSONObject json1= HttpUtil.httpPost(url, object1,false);
//						log.info("请求服务器状态"+json1.get("result"));
						break;

					case 112: // 3.检测按钮状态指令数据处理״̬
						JSONObject object2 = JCDataUtil.parseDoorStateTwo(b);
						client.publishMessage(topic,object2.toJSONString());
//						JSONObject json2 = HttpUtil.httpPost(url, object2,false);
//						log.info("请求服务器状态"+json2.get("result").toString());
						break;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
		
	}


	/**
	  * 字节数组转为string
	  * @param bArray
	  * @return HexString
	  */
	 public static final String bytesToHexString(byte[] bArray) {
		  StringBuffer sb = new StringBuffer(bArray.length);
		  String sTemp;
		  for (int i = 0; i < bArray.length; i++) {
			   sTemp = Integer.toHexString(0xFF & bArray[i]);
			   if (sTemp.length() < 2)
			   sb.append(0);
			   sb.append(sTemp.toUpperCase());
		  }
		  return sb.toString();
	 }

	/**
	 * int类型转byte数组
	 * @param value
	 * @return
	 */
	public static byte[] int2Bytes(int value ) {
		byte[] src = new byte[4];
		src[3] =  (byte) ((value>>24) & 0xFF);
		src[2] =  (byte) ((value>>16) & 0xFF);
		src[1] =  (byte) ((value>>8) & 0xFF);
		src[0] =  (byte) (value & 0xFF);
		return src;
	}

	/**
	 * System.arraycopy()方法
	 * 合并两个byte数组
	 * @param bt1
	 * @param bt2
	 * @return
	 */
	public static byte[] byteMerger(byte[] bt1, byte[] bt2){
		byte[] bt3 = new byte[bt1.length+bt2.length];
		System.arraycopy(bt1, 0, bt3, 0, bt1.length);
		System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
		return bt3;
	}
}
